<script setup lang="ts">
import { onMounted, ref } from 'vue'

type AppVersion = {
  version: string
  date?: string
}
let currentVersion: string | null = null
let timer: number | null = null
const VERSION_URL = '/version.json'
const open = ref<boolean>(false)

const fetchVersion = async (): Promise<AppVersion | null> => {
  try {
    const res = await fetch(`${VERSION_URL}?t=${Date.now()}`, { cache: 'no-store' })
    if (!res.ok) return null
    return (await res.json()) as AppVersion
  } catch {
    return null
  }
}

const startVersionPolling = async (options?: { intervalMs?: number }) => {
  const intervalMs = options?.intervalMs ?? 60_000

  const first = await fetchVersion()
  if (first?.version) currentVersion = first.version

  if (timer) window.clearInterval(timer)
  timer = window.setInterval(async () => {
    const meta = await fetchVersion()
    if (!meta?.version) return
    if (currentVersion && meta.version !== currentVersion) {
      open.value = true
      window.clearInterval(timer!)
      timer = null
      return
    }
    currentVersion = meta.version
  }, intervalMs)
}
const windowReload = () => {
  location.reload()
}
onMounted(() => {
  // 可以指定每次轮询间隔时间 单位：毫秒
  startVersionPolling({ intervalMs: 30000 })
  console.log('============================版本检测机制开启============================')
})
</script>

<template>
  <a-modal v-model:open="open" title="发现新版本" :maskClosable="false" :keyboard="false">
    <p>检测到新版本,是否刷新以获取最新内容？</p>
    <template #footer>
      <a-button @click="open = false">稍后</a-button>
      <a-button type="primary" @click="windowReload">刷新</a-button>
    </template>
  </a-modal>
</template>

<style scoped></style>
